<template>
  <div class="app-container">
    <div>
      <el-button type="primary" plain @click="showCaigouApplyDialog">采购申请</el-button>
    </div>
    <!-- {{list}} -->
    <div style="padding: 10px" />
    <el-table
      v-loading="listLoading"
      :data="list"
      style="width: 100%"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="状态" align="center" width="100px">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sta==0 && scope.row.chexiao==0" type="warning">审核</el-tag>
          <el-tag v-if="scope.row.sta==1 && scope.row.chexiao==0" type="success">通过</el-tag>
          <el-tag v-if="scope.row.sta==2 && scope.row.chexiao==0" type="danger">拒绝</el-tag>
          <el-tag v-if="scope.row.chexiao==1" type="info">撤销</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="申请编号" align="center" width="100px">
        <template slot-scope="scope">
          <el-tag> {{ scope.row.id }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="申请时间" align="center" width="110px">
        <template slot-scope="scope">
          {{ getFormatedTimeStr(scope.row.createTime) }}
        </template>
      </el-table-column>

      <el-table-column label="申请部门" align="center">
        <template slot-scope="scope">
          {{ scope.row.department }}
        </template>
      </el-table-column>

      <el-table-column label="采购方式" align="center">
        <template slot-scope="scope">
          {{ scope.row.fangshi }}
        </template>
      </el-table-column>

      <el-table-column label="采购类别" align="center">
        <template slot-scope="scope">
          {{ scope.row.leibie }}
        </template>
      </el-table-column>

      <!-- <el-table-column label="清单" align="center">
        <template slot-scope="scope">
          <div v-for="(item,idx) in scope.row.items" :key="idx">{{ item.name }} : {{ item.price }}元 X {{ item.cnt }}个 =
            {{ item.total }}元
          </div>
        </template>
      </el-table-column> -->

      <el-table-column label="采购清单" align="center">
        <template slot-scope="scope">
          <p v-for="(item,index) in scope.row.attaches " :key="index" style="">
            <el-link :href="item.path" type="primary" target="_blank">{{ item.name }}</el-link>
          </p>
        </template>
      </el-table-column>

      <el-table-column label="总价合计" align="center">
        <template slot-scope="scope">
          ￥ {{ scope.row.totalMoney }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250px">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" plain @click="seeDetail(scope.row.id)">详情 </el-button>
          <el-button v-if="scope.row.sta>0 && scope.row.chexiao == 0" size="mini" type="primary" plain @click="printPdf(scope.row.id)">生成PDF </el-button>
          <el-button v-if="(scope.row.chexiao == 0)" size="mini" type="danger" plain @click="revertApply(scope.$index)">撤回 </el-button>
        </template>
      </el-table-column>

    </el-table>

    <div style="padding: 10px" />
    <el-pagination
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageCount"
      layout="total, sizes, prev, pager, next, jumper"
      :total="dataTotal"
      @size-change="onPageSizeChange"
      @current-change="onCurrentPageChange"
    />

    <el-dialog
      :visible.sync="caigouApplyDialog.visible"
      width="50%"
      :close-on-click-modal="false"
      top="5vh"
      center
      :show-close="false"
    >
      <div>
        <el-form ref="form" size="mini" label-position="left" label-width="100px">
          <el-row>
            <!-- 左侧 -->
            <el-col :span="15">
              <div class="title"><i class="el-icon-document" /> 申请单</div>
              <el-form-item label="采购方式">
                <el-radio-group v-model="caigouApplyDialog.fangshi" size="mini" text-color="#fff" fill="#0b847b">
                  <el-radio-button label="统一采购(办公室)">统一采购(办公室)</el-radio-button>
                  <el-radio-button label="自行采购">自行采购</el-radio-button>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="采购类别">
                <el-radio-group v-model="caigouApplyDialog.leibie" size="mini" text-color="#fff" fill="#0b847b">
                  <el-radio-button label="办公用品">办公用品</el-radio-button>
                  <el-radio-button label="办公电脑">办公电脑</el-radio-button>
                  <el-radio-button label="办公家具">办公家具</el-radio-button>
                  <el-radio-button label="设备零件">设备零件</el-radio-button>
                  <el-radio-button label="其他">其他</el-radio-button>
                </el-radio-group>
              </el-form-item>

              <!-- 物品清单 -->
              <!-- <el-form-item label="采购明细" />
              <el-row style="padding-bottom:5px ;font-style: italic;">
                <el-col :span="4">物品名称</el-col>
                <el-col :span="8">用途</el-col>
                <el-col :span="4">数量</el-col>
                <el-col :span="4">单价</el-col>
                <el-col :span="4">合计</el-col>
              </el-row> -->
              <!-- <div v-for="(item1, idx1) in caigouApplyDialog.items" :key="idx1">
                <el-row>
                  <el-col :span="4">
                    <el-input v-model="item1.name" />
                  </el-col>
                  <el-col :span="8">
                    <el-input v-model="item1.usage" />
                  </el-col>
                  <el-col :span="4">
                    <el-input v-model="item1.cnt" type="number" @change="itemNumberChange" />
                  </el-col>
                  <el-col :span="4">
                    <el-input v-model="item1.price" type="number" @change="itemNumberChange" />
                  </el-col>
                  <el-col :span="4">
                    <el-input v-model="item1.total" disabled />

                  </el-col>
                </el-row>
              </div>
              <div style="padding-bottom: 5px;" />
              <el-button type="primary" size="mini" plain @click="clickAddItem">增加采购清单</el-button>
              <div style="padding-bottom: 5px;" /> -->

              <el-form-item label="采购总计">
                <!-- <span style="color: indianred;font-size: 18px;font-weight: bold">￥{{ caigouApplyDialog.totalMoney }}</span> -->
                <el-input v-model="caigouApplyDialog.totalMoney" type="number" />
              </el-form-item>

              <el-form-item label="采购清单">
                <el-upload ref="attaches" multiple :action="uploadconfig.url" :on-success="uploadAttachSuccess">
                  <el-button size="mini" type="primary" plain>点击上传附件</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
            <!-- 右侧 -->
            <el-col :span="8" :offset="1">
              <div class="title"><i class="el-icon-s-check" /> 审核流程</div>
              <div v-for="(item,index) in caigouApplyDialog.auditors" :key="index">
                <!-- 箭头：第一个不显示 -->
                <div v-if="index>0" class="step-arrow">
                  <el-row>
                    <el-col :span="8">
                      <div><i class="el-icon-caret-bottom" /></div>
                    </el-col>
                  </el-row>
                </div>
                <!-- 步骤样式 -->
                <div class="step">
                  <el-row>
                    <el-col :span="8">
                      <div class="step-info-left">{{ item.stepName || item.positionName }}</div>
                    </el-col>
                    <el-col :span="16">
                      <div class="step-info-right">{{ item.name }}</div>
                    </el-col>
                  </el-row>
                </div>
              </div>
            </el-col>
          </el-row>

        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="caigouApplyDialog.visible = false">关 闭</el-button>
        <el-button type="primary" @click="clickApply()">提 交</el-button>
      </span>
    </el-dialog>

    <el-dialog title="" width="60%" :visible.sync="detailDialog.visible" top="5vh">
      <caigou-detail :id="detailDialog.id" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="(detailDialog.visible = false)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  websock
} from '@/websock'
import {
  uploadconfig
} from '@/const'
import { quchongAuditors } from '@/utils/utils'
import moment from 'moment'
import CaigouDetail from '../../components/details/caigouDetail.vue'

export default {
  components: { CaigouDetail },
  filters: {
    statusFilter(sta) {
      const statusMap = {
        1: 'info',
        2: 'success',
        3: 'danger'
      }
      return statusMap[sta]
    }
  },
  data() {
    return {
      uploadconfig,
      // 人员列表样式(多选)
      props: {
        multiple: true
      },
      // 人员列表数据
      userList: [],
      list: null,
      listLoading: true,
      pageIndex: 1,
      pageCount: 10,
      dataTotal: 0,
      departmentList: null,
      userInfo: {},
      caigouApplyDialog: {
        visible: false,
        department: '',
        fangshi: '',
        leibie: '',
        items: [{
          name: '',
          usage: '',
          cnt: '0',
          price: '0',
          total: '0'
        }],
        totalMoney: '0',
        auditors: [],
        attaches: []
      },
      detailDialog: {
        visible: false,
        id: 0
      }
    }
  },
  async created() {
    this.userInfo = await websock.getUserInfo()
    this.getList()
    websock.getDepartList().then((data) => {
      this.departmentList = data
    })

    const res = await websock.getContactList()
    console.log('created', res)
    const userList = []
    for (let i = 0; i !== res.length; i++) {
      userList.push({
        value: i + '',
        label: res[i].name,
        children: []
      })
      for (let j = 0; j !== res[i].userList.length; j++) {
        userList[i].children.push({
          value: res[i].userList[j].uid,
          label: res[i].userList[j].name
        })
      }
    }
    this.userList = userList

    const auditors = await websock.getAuditors({ typ: 13 })
    console.log('auditors', auditors)
    quchongAuditors(auditors)
    this.caigouApplyDialog.auditors = auditors
  },
  methods: {
    // 获取格式化时间字符串
    getFormatedTimeStr(stamp, str = 'MM-DD HH:mm') {
      return moment(stamp).format(str)
    },
    getList() {
      this.listLoading = true
      websock.caigouApplyRecordWeb({
        pageIndex: this.pageIndex,
        pageCount: this.pageCount,
        name: this.searchname || ''
      }).then(
        (data) => {
          this.listLoading = false
          this.list = data.list
          this.dataTotal = data.count
        }
      )
    },
    onPageSizeChange(val) {
      this.pageCount = val
      this.getList()
    },
    onCurrentPageChange(val) {
      this.pageIndex = val
      this.getList()
    },
    showCaigouApplyDialog() {
      this.caigouApplyDialog.visible = true
      this.caigouApplyDialog.department = this.departmentList[0].name
      this.caigouApplyDialog.fangshi = '统一采购(办公室)'
      this.caigouApplyDialog.leibie = '办公用品'
      this.caigouApplyDialog.items = [{
        name: '',
        usage: '',
        cnt: '0',
        price: '0',
        total: '0'
      }]
      this.caigouApplyDialog.totalMoney = 0
      this.caigouApplyDialog.attaches = []
      if (this.$refs.attaches) this.$refs.attaches.uploadFiles = []
    },
    clickAddItem() {
      this.caigouApplyDialog.items.push({
        name: '',
        usage: '',
        cnt: '0',
        price: '0',
        total: '0'
      })
    },
    itemNumberChange() {
      let allMoney = 0
      for (let i = 0; i != this.caigouApplyDialog.items.length; i++) {
        let itemMoney = 0
        const cnt = parseInt(this.caigouApplyDialog.items[i].cnt) || 0
        this.caigouApplyDialog.items[i].cnt = cnt + ''
        const price = parseFloat(this.caigouApplyDialog.items[i].price) || 0
        this.caigouApplyDialog.items[i].price = price + ''
        itemMoney = cnt * price
        this.caigouApplyDialog.items[i].total = itemMoney + ''
        allMoney += itemMoney
      }

      this.caigouApplyDialog.totalMoney = allMoney + ''
    },
    uploadAttachSuccess(res, file) {
      console.log('upload attach success', res, file)
      if (res.code !== 0) {
        return this.$message.error(res.message || 'error')
      }
      this.caigouApplyDialog.attaches.push({
        name: file.name,
        path: res.data
      })
    },
    async clickApply() {
      console.log('click apply', this.caigouApplyDialog)

      if (this.caigouApplyDialog.auditors.length == 0) return this.$message.error('请选择审核人')
      // for (let i = 0; i != this.caigouApplyDialog.items.length; i++) {
      //   if (!this.caigouApplyDialog.items[i].name) return this.$message.error('请输入物品名称')
      //   if (!this.caigouApplyDialog.items[i].usage) return this.$message.error('请输入物品用途')
      //   if (!this.caigouApplyDialog.items[i].cnt) return this.$message.error('请输入物品数量')
      //   if (!this.caigouApplyDialog.items[i].price) return this.$message.error('请输入物品单价')
      // }

      const auditors = []
      for (let i = 0; i != this.caigouApplyDialog.auditors.length; i++) {
        auditors.push({ uid: this.caigouApplyDialog.auditors[i].uid, stepName: this.caigouApplyDialog.auditors[i].stepName || this.caigouApplyDialog.auditors[i].positionName })
      }

      try {
        await websock.caigouApply({
          department: this.userInfo.departmentName,
          fangshi: this.caigouApplyDialog.fangshi,
          leibie: this.caigouApplyDialog.leibie,
          items: this.caigouApplyDialog.items,
          totalMoney: this.caigouApplyDialog.totalMoney,
          attaches: this.caigouApplyDialog.attaches,
          auditors
        })

        this.$message.success('申请成功,等待审核')

        this.caigouApplyDialog.visible = false

        this.getList()
      } catch (err) {
        console.error(err)
        this.$message.error(err.message || 'err')
      }
    },
    async revertApply(idx) {
      try {
        await websock.revertCaigouApply({
          id: this.list[idx].id
        })
        this.list[idx].sta = 4
        this.getList()
      } catch (err) {
        console.error(err)
        this.$message.error({
          title: err.message || 'error'
        })
      }
    },
    seeDetail(id) {
      this.detailDialog.visible = true
      this.detailDialog.id = id
    },
    printPdf(id) {
      websock.printPdf({ typ: 13, id }).then(res => {
        console.log('print pdf', res)
        const a = document.createElement('a')
        a.style.display = 'none'
        a.href = res
        a.target = '_blank'
        document.body.appendChild(a)
        a.click()

        URL.revokeObjectURL(a.href)
        document.body.removeChild(a)
      })
    }
  }
}
</script>

<style>
  @import url("../../styles/form.css");
</style>
